#! F:\Python\python.exe
#coding=utf-8

from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler, CGIXMLRPCRequestHandler
from SocketServer import ThreadingMixIn
from skydbobject import *
from sqlalchemy.types import *
import sqlalchemy
import time, threading

class contactField():
    def __init__(self, fieldID = 0):
        self.fieldID = fieldID
        self.attrValueArray = []

class CAssistant():
    def __init__(self, id):
        """id is skyWalker's account."""
        self.strAccount_ = id
        
    def getUserInfo (self, iPageNum, iPageSize, strWhere, type):
        """ Get user informations from DataBase which is condition with strWhere.
        
        in parameters description:
        iPageNum 
          pagination number.
        iPageSize
          how many users on one page.
        strWhere
          the condition with user information.
          must like "tmpTbl.nickName LIKE 'x%'"
        
        out parameters description:
        iTotalSize
          total number of one user's friends.
        records
          all user informations in data base.
          it are many lists.
        """
        #dbPageNum = iPageNum + 1
        #begin get userID(integer) by accounts in database
        dbengine = sqlalchemy.create_engine(g_DBConnectionStr)
        session = sqlalchemy.create_session()
        queryObj = session.query(skyUserInfoObj).selectfirst(skyUserInfoObj.c.accounts == self.strAccount_)
        userID = queryObj.userID
        #end get userID(integer) by accounts in database
        strDBSP = "exec GetPagingData\
                @tablename = '%(tablename)s',\
                @fieldlist = %(fieldlist)s,\
                @orderfield = %(orderfield)s,\
                @orderfield2 = %(orderfield2)s,\
                @keyfield = %(keyfield)s,\
                @pageindex =%(pageindex)d,\
                @pagesize = %(pagesize)d,\
                @strwhere = '%(strwhere)s',\
                @ordertype = %(ordertype)d,\
                @iscount = %(iscount)d"
        if 1 == type :
            tablename = "(select userID,accounts,password,nickName,email,address,myUrl,myPhoto,imTool,sceneID,totalFrequency,remark,modifyTime,searchmsg from LocalUserInfo where skyUserID = :skyUserID union select userID,accounts,password,nickName,email,address,myUrl,myPhoto,imTool,sceneID,totalFrequency,remark,modifyTime,searchmsg from skyUserInfo where userID in (select friendID from skyUserRelation where userID = :skyUserID)) as tmpTbl "
            if strWhere != "" :
                strWhere += " and userID <> %(myUserID)d " %{'myUserID' : userID}
            else:
                strWhere += "  userID <> %(myUserID)d " %{'myUserID' : userID}
        elif 0 == type:
            tablename = "skyUserInfo as tmpTbl "
            if strWhere != "" :
                strWhere += " and userID not in \
                (select friendID from skyUserInfo, skyUserRelation  \
                where skyUserInfo.userID = %(myUserID)d and skyUserInfo.userID = skyUserRelation.userID) \
                and userID <> %(myUserID)d " %{'myUserID' : userID}
            else:
                strWhere += " userID not in \
                (select friendID from skyUserInfo, skyUserRelation  \
                where skyUserInfo.userID = %(myUserID)d and skyUserInfo.userID = skyUserRelation.userID) \
                and userID <> %(myUserID)d " %{'myUserID' : userID}
        isCount = 1
        print  strDBSP % {'tablename' : tablename, 
                                  'fieldlist' : "'*'", 
                                  'orderfield' : "'[userID] '" , 
                                  'orderfield2' : "'[totalFrequency]'", 
                                  'keyfield' : "'[userID]'", 
                                  'pageindex' : iPageNum, 
                                  'pagesize' : iPageSize, 
                                  'strwhere' : " " + strWhere, 
                                  'ordertype' : 1, 
                                  'iscount': isCount }
        
        totalSizeProxy = sqlalchemy.text (strDBSP % {'tablename' : tablename, 
                                  'fieldlist' : "'*'", 
                                  'orderfield' : "'[userID] '" , 
                                  'orderfield2' : "'[totalFrequency]'", 
                                  'keyfield' : "'[userID]'", 
                                  'pageindex' : iPageNum, 
                                  'pagesize' : iPageSize, 
                                  'strwhere' : " " + strWhere, 
                                  'ordertype' : 1, 
                                  'iscount': isCount } , dbengine).execute(skyUserID = userID)
        totalSize = totalSizeProxy.fetchall()[0][0]
        
        isCount = 0
        recordsProxy = sqlalchemy.text (strDBSP % {'tablename' : tablename, 
                                  'fieldlist' : "'*'", 
                                  'orderfield' : "'[userID] '" , 
                                  'orderfield2' : "'[totalFrequency]'", 
                                  'keyfield' : "'[userID]'", 
                                  'pageindex' : iPageNum, 
                                  'pagesize' : iPageSize, 
                                  'strwhere' : " " + strWhere, 
                                  'ordertype' : 1, 
                                  'iscount' : isCount} , dbengine).execute(skyUserID = userID)
        return totalSize, recordsProxy.fetchall() 


    def getUserInfo_temp(self, iPageNum, iPageSize, strWhere, type):
        """ Get user informations from DataBase which is condition with strWhere.
        
        in parameters description:
        iPageNum 
          pagination number.
        iPageSize
          how many users on one page.
        strWhere
          the condition with user information.
          must like "tmpTbl.nickName LIKE 'x%'"
        
        out parameters description:
        iTotalSize
          total number of one user's friends.
        records
          all user informations in data base.
          it are many lists.
        """
        dbPageNum = iPageNum + 1
        dbengine = sqlalchemy.create_engine(g_DBConnectionStr)
        session = sqlalchemy.create_session()
        queryObj = session.query(skyUserInfoObj).selectfirst(skyUserInfoObj.c.accounts == self.strAccount_)
        userID = queryObj.userID
        strDBSP = """exec pagination  @tblName = %(tblName)s,     
                @strGetFields = %(strGetFields)s,      
                @fldName = %(fldName)s,     
                @PageSize = %(PageSize)s,     
                @PageIndex = %(PageIndex)d,     
                @doCount = %(doCount)d,     
                @OrderType = %(OrderType)d,     
                @strWhere = '%(strWhere)s'  """
        
        isCount = 1
        if 1 == type :
            tblName = "'(select userID,accounts,password,nickName,email,address,myUrl,myPhoto,imTool,sceneID,totalFrequency,remark,modifyTime,searchmsg from LocalUserInfo where skyUserID = :skyUserID union select userID,accounts,password,nickName,email,address,myUrl,myPhoto,imTool,sceneID,totalFrequency,remark,modifyTime,searchmsg from skyUserInfo where userID in (select friendID from skyUserRelation where userID = :skyUserID)) as tmpTbl '"
        elif 0 == type:
            tblName = "'skyUserInfo as tmpTbl'"
        elif 2 == type:
            tblName = "'skyUserInfo as tmpTbl'"
            if strWhere != "" :
                strWhere += " and userID not in \
                (select friendID from skyUserInfo, skyUserRelation \
                where skyUserInfo.userID = %(myUserID)d and skyUserInfo.userID = skyUserRelation.userID) \
                and userID <> %(myUserID)d order by [userid] asc " %{'myUserID' : userID}
            else:
                strWhere += " userID not in \
                (select friendID from skyUserInfo, skyUserRelation \
                where skyUserInfo.userID = %(myUserID)d and skyUserInfo.userID = skyUserRelation.userID) \
                and userID <> %(myUserID)d order by [userid] asc" %{'myUserID' : userID}
        
        # strDBSPTemp = strDBSP ################################################
        print strDBSP % {'tblName' : tblName, 
                                  'strGetFields' : "'*'", 
                                  'fldName' : "'[totalFrequency] '" , 
                                  'PageSize' : iPageSize, 
                                  'PageIndex' : dbPageNum, 
                                  'doCount' : isCount, 
                                  'OrderType' : 1, 
                                  'strWhere' : " " + strWhere} 
        
        totalSizeRecord = sqlalchemy.text (strDBSP % {'tblName' : tblName, 
                                 'strGetFields' : "'*'", 
                                 'fldName' : "'[totalFrequency] '", 
                                 'PageSize' : iPageSize, 
                                 'PageIndex' : dbPageNum, 
                                 'doCount' : isCount, 
                                 'OrderType' : 1, 
                                 'strWhere' : " " + strWhere}, dbengine).execute(skyUserID = userID)
        totalSize = totalSizeRecord.fetchone()[0]
        isCount = 0
        recordsProxy = sqlalchemy.text (strDBSP % {'tblName' : tblName, 
                         'strGetFields' : "'*'", 
                         'fldName' : "'[totalFrequency] '", 
                         'PageSize' : iPageSize, 
                         'PageIndex' : dbPageNum, 
                         'doCount' : isCount, 
                         'OrderType' : 1, 
                         'strWhere' : " " + strWhere}, dbengine).execute(skyUserID = userID)
        return totalSize, recordsProxy.fetchall() 
    

class SkyPimManager():
    def __init__(self, id):
        self.id_ = id 
        self.session = None  
        self.transaction = None 
        self.timer = None
        
    def getDetail(self, id):
        print "\ngetDetail()\n"
        session = sqlalchemy.create_session()
        
        item = Sky.ContactItem(nameSeq = [], 
                                phoneSeq = [], 
                                emailSeq = [], 
                                addrSeq = [], 
                                urlSeq = [], 
                                photoSeq = [], 
                                remarkSeq = [], 
                                imSeq = [], 
                                sceneSeq = [])
        if(id[0] == '_'):
            userInfo = session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
            localUserInfo = session.query(LocalUserInfoObj).selectfirst_by(accounts = id, skyUserID = userInfo.userID)
            if localUserInfo != None :
                item.id = localUserInfo.accounts
                if localUserInfo.nickName != "":
                    item.nameSeq.append(localUserInfo.nickName)
                if localUserInfo.email != "":
                    item.emailSeq.append(localUserInfo.email)
                if localUserInfo.address != "":
                    item.addrSeq.append(localUserInfo.address)
                if localUserInfo.myUrl != "":
                    item.urlSeq.append(localUserInfo.myUrl)
                if localUserInfo.myPhoto != None:
                    item.photoSeq.append(localUserInfo.myPhoto)
                if localUserInfo.remark != "":
                    item.remarkSeq.append(localUserInfo.remark)
                if localUserInfo.imTool != "":
                    item.imSeq.append(localUserInfo.imTool)
                item.defaultScene = localUserInfo.sceneID
                item.lastModified = localUserInfo.modifyTime

                sceneList = session.query(skySceneObj).select_by(userID = localUserInfo.userID)
                for scene in sceneList:
                    scenseItem = Sky.ContactScene()
                    scenseItem.sceneName = scene.sceneName
                    scenseItem.touchFrequency = scene.touchFrequency
                    
                    userPhone = session.query(skyUserPhoneObj).selectfirst_by(userID = localUserInfo.userID, phoneIndex = scene.phoneIndex)
                    if userPhone != None:
                        if userPhone.phoneNum not in item.phoneSeq:
                            item.phoneSeq.append(userPhone.phoneNum)
                        phoneIndex = item.phoneSeq.index(userPhone.phoneNum)
                        scenseItem.phoneIdx = phoneIndex
                        item.sceneSeq.append(scenseItem)
                    else:
                        error = "phoneNum of the table(skySceneObj) cannot find in the table(skyUserPhoneObj)"
                        raise error
            else:
                error = "localFriend is not in the table(LocalUserInfoObj)"
                raise error
                
        
        else:
            userInfo = session.query(skyUserInfoObj).selectfirst_by(accounts = id)
            if userInfo != None:
                item.id = userInfo.accounts
                if userInfo.nickName != "":
                    item.nameSeq.append(userInfo.nickName)
                if userInfo.email != "":
                    item.emailSeq.append(userInfo.email)
                if userInfo.address != "":
                    item.addrSeq.append(userInfo.address)
                if userInfo.myUrl != "":
                    item.urlSeq.append(userInfo.myUrl)
                if userInfo.myPhoto != None:
                    item.photoSeq.append(userInfo.myPhoto)
                if userInfo.remark != "":
                    item.remarkSeq.append(userInfo.remark)
                if userInfo.imTool != "":
                    item.imSeq.append(userInfo.imTool)
                item.defaultScene = userInfo.sceneID
                item.lastModified = userInfo.modifyTime
                                        
                sceneList = session.query(skySceneObj).select_by(userID = userInfo.userID)

                for scene in sceneList:
                    scenseItem = Sky.ContactScene()
                    scenseItem.sceneName = scene.sceneName
                    scenseItem.touchFrequency = scene.touchFrequency
                    
                    userPhone = session.query(skyUserPhoneObj).selectfirst_by(userID = userInfo.userID, phoneIndex = scene.phoneIndex)
                    if userPhone != None:
                        if userPhone.phoneNum not in item.phoneSeq:
                            item.phoneSeq.append(userPhone.phoneNum)
                        phoneIndex = item.phoneSeq.index(userPhone.phoneNum)
                        scenseItem.phoneIdx = phoneIndex
                        item.sceneSeq.append(scenseItem)
                    else:
                        error = "phoneNum of the table(skySceneObj) cannot find in the table(skyUserPhoneObj)"
                        raise error
            else:
                error = "skyFriend is not in the table(skyUserInfoObj)"
                raise error
            
        print "\nEnd getDetail()\n"
        return item
    

    def getNext(self, pageNum, pageSize):
        print 'pageNum = ', pageNum, 'pageSize = ' , pageSize
        print "\ngetNext()\n"
        
        strWhere = "";
        assistant = CAssistant(self.id_)
        totalSize, recordList = assistant.getUserInfo(pageNum, pageSize, strWhere, type = 1)
        
        print 'totalRecord = ', totalSize, '\n', 'recordList = ', recordList
        
        session = sqlalchemy.create_session()
        contactList = []
        for onRecord in recordList :
            item = Sky.ContactItem(id=onRecord[1], 
                                   nameSeq=[], 
                                   phoneSeq=[], 
                                   emailSeq=[], 
                                   addrSeq=[], 
                                   urlSeq=[], 
                                   photoSeq=[], 
                                   remarkSeq=[], 
                                   imSeq=[], 
                                   sceneSeq=[], 
                                   defaultScene= onRecord[9], 
                                   lastModified= onRecord[12])
            
            if onRecord[3] != "":
                item.nameSeq.append(onRecord[3])
            if onRecord[4] != "":
                item.emailSeq.append(onRecord[4])
            if onRecord[5] != "":
                item.addrSeq.append(onRecord[5])
            if onRecord[6] != "":
                item.urlSeq.append(onRecord[6])
            if onRecord[7] != None:
                item.photoSeq.append(onRecord[7])
            if onRecord[11] != "":
                item.remarkSeq.append(onRecord[11])
            if onRecord[8] != "":
                item.imSeq.append(onRecord[8])
            
            sceneList = session.query(skySceneObj).select_by(userID = onRecord[0])
            for scene in sceneList :
                scenseItem = Sky.ContactScene()
                scenseItem.sceneName = scene.sceneName
                scenseItem.touchFrequency = scene.touchFrequency
                
                print 'my id = ', onRecord[0]
                print 'phoneIndex = ', scene.phoneIndex
                
                userPhone = session.query(skyUserPhoneObj).selectfirst_by(userID = onRecord[0], phoneIndex = scene.phoneIndex)
                print userPhone
                if userPhone != None:
                    if userPhone.phoneNum not in item.phoneSeq:
                        item.phoneSeq.append(userPhone.phoneNum)
                    phoneIndex = item.phoneSeq.index(userPhone.phoneNum)
                    scenseItem.phoneIdx = phoneIndex
                    item.sceneSeq.append(scenseItem)
                else:
                    error = "phoneNum of the table(skySceneObj) cannot find in the table(skyUserPhoneObj)"
                    raise error

            contactList.append(item)
    
        print "\nEnd getNext()\n"
        return totalSize, contactList 
        
    def find(self, context, pageNum, pageSize, type):
        print "\nfind()\n"
        if context != "" :
            if type == 1:
                strWhere = " tmpTbl.searchmsg LIKE ''%%" + context + "%%'' "
            else:
                strWhere = " tmpTbl.nickName LIKE ''%%" + context + "%%'' "
        else:
            strWhere = ""
        assistant = CAssistant(self.id_)
        totalSize, recordList = assistant.getUserInfo(pageNum, pageSize, strWhere, type)
        
        
        #print len(recordList)
        #print totalSize
        print "__LINE NUMBER 282"
        session = sqlalchemy.create_session()
        contactList = []
        #print recordList
        for friend in recordList:
            item = Sky.ContactItem(id=friend[1], 
                                   nameSeq=[], 
                                   phoneSeq=[], 
                                   emailSeq=[], 
                                   addrSeq=[], 
                                   urlSeq=[], 
                                   photoSeq=[], #friend[7]
                                   remarkSeq=[], 
                                   imSeq=[], 
                                   sceneSeq=[], 
                                   defaultScene=friend[9], 
                                   lastModified=friend[12])
            
            if friend[3] != "":
                item.nameSeq.append(friend[3])
            if friend[4] != "":
                item.emailSeq.append(friend[4])
            if friend[5] != "":
                item.addrSeq.append(friend[5])
            if friend[6] != "":
                item.urlSeq.append(friend[6])
            if friend[7] != None:
                item.photoSeq.append(friend[7])
            if friend[11] != "":
                item.remarkSeq.append(friend[11])
            if friend[8] != "":
                item.imSeq.append(friend[8])
            #print "__LINE NUMBER 298 and friend =", friend
            sceneList = session.query(skySceneObj).select_by(userID = friend[0])
            for scene in sceneList :
                scenseItem = Sky.ContactScene()
                scenseItem.sceneName = scene.sceneName
                scenseItem.touchFrequency = scene.touchFrequency
                
                userPhone = session.query(skyUserPhoneObj).selectfirst_by(userID = friend[0], phoneIndex = scene.phoneIndex)
                if userPhone != None:
                    if userPhone.phoneNum not in item.phoneSeq:
                        item.phoneSeq.append(userPhone.phoneNum)
                    phoneIndex = item.phoneSeq.index(userPhone.phoneNum)
                    scenseItem.phoneIdx = phoneIndex
                    item.sceneSeq.append(scenseItem)
                else:
                    error  = "phoneNum of the table(skySceneObj) cannot find in the table(skyUserPhoneObj)"
                    raise error
                    
            contactList.append(item)
        #print "__LINE NUMBER 314 and", len( contactList )   
        print "contactList = \n { \n", contactList, "\n }"
        print "totalSize = ", totalSize
        print "len(contactList) = " , len(contactList), "\n"
        print "\nEnd find()\n"
        return totalSize, contactList

    def delete(self, idList):
        print "\ndelete()\n"
        session = sqlalchemy.create_session()
        transaction=session.create_transaction()
        try:
            user = session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
            for idIndex in range(len(idList)):
                if(idList[idIndex][0] == '_'):
                    localFriend = session.query(LocalUserInfoObj).selectfirst_by(accounts = idList[idIndex], skyUserID = user.userID) 
                    if localFriend != None:
                        session.query(LocalUserInfoObj_bak1)
                        session.save(localFriend)
                        session.query(LocalUserInfoObj)
                        session.delete(localFriend)
                        session.flush()
                        localFriendSceneList = session.query(skySceneObj).select_by(userID = localFriend.userID) 
                        for localFriendScene in localFriendSceneList :
                            session.query(skySceneObj_bak1)
                            session.save(localFriendScene)
                            session.query(skySceneObj)
                            session.delete(localFriendScene)
                            session.flush()
                        userPhoneList = session.query(skyUserPhoneObj).select_by(userID = localFriend.userID) 
                        for userPhone in userPhoneList :
                            session.query(skyUserPhoneObj_bak1)
                            session.save(userPhone)
                            session.query(skyUserPhoneObj)
                            session.delete(userPhone)
                            session.flush()
                
                else:
                    user = session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_) 
                    friend = session.query(skyUserInfoObj).selectfirst_by(accounts = idList[idIndex])
                    if friend != None:
                        relation =  session.query(skyUserRelationObj).selectfirst_by(userID = user.userID, friendID = friend.userID)
                        if relation != None:
                            session.delete(relation)
                            session.flush()
                    
            transaction.commit()
        except:
            transaction.rollback()
            raise
        
        print "\nEnd delete()\n"
        return True

    def add(self, contactList):
        print "\nadd()\n"
        print locals()
        session = sqlalchemy.create_session() 
        transaction=session.create_transaction()
        try:
            user = session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
            for contactItem in contactList:
                sceneNameList = []
                for sceneItem in contactItem.sceneSeq:
                    sceneNameList.append(sceneItem.sceneName)
                for sceneNameItem in sceneNameList:
                    count = sceneNameList.count(sceneNameItem)
                    if count > 1:
                        error = "sceneName repeat"
                        raise error
                    
                if(contactItem.id[0] == '_'):
                    if len(contactItem.sceneSeq) == 0 or len(contactItem.phoneSeq) == 0:
                        error = "localFriend  have not scene or phone"
                        raise error
                    
                    localFriendItem = session.query(LocalUserInfoObj).selectfirst_by(accounts = contactItem.id, skyUserID = user.userID)
                    if localFriendItem != None:
                        error = "localFriend is in the table(LocalUserInfoObj)"
                        raise error
                    
                    localFriend = LocalUserInfoObj()
                    localFriend.skyUserID = user.userID
                    localFriend.accounts = contactItem.id
                    localFriend.searchmsg = ""
                    if len(contactItem.nameSeq) != 0:
                        localFriend.nickName = contactItem.nameSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.nickName
                    else:
                        localFriend.nickName = ""
                    if len(contactItem.emailSeq) != 0:
                        localFriend.email = contactItem.emailSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.email
                    else:
                        localFriend.email = ""
                    if len(contactItem.addrSeq) != 0:
                        localFriend.address = contactItem.addrSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.address
                    else:
                        localFriend.address = ""
                    if len(contactItem.urlSeq) != 0:
                        localFriend.myUrl = contactItem.urlSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.myUrl
                    else:
                        localFriend.myUrl = ""
                    if len(contactItem.photoSeq) != 0:
                        localFriend.myPhoto = contactItem.photoSeq[0]
                    else:
                        localFriend.myPhoto = None
                    if len(contactItem.imSeq) != 0:
                        localFriend.imTool = contactItem.imSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.imTool
                    else:
                        localFriend.imTool = ""
                    if len(contactItem.remarkSeq) != 0:
                        localFriend.remark = contactItem.remarkSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.remark
                    else:
                        localFriend.remark = ""
                        
                    for phoneNum in contactItem.phoneSeq:
                        localFriend.searchmsg = localFriend.searchmsg + "-" + str(phoneNum)
                        
                    localFriend.sceneID = contactItem.defaultScene
                    localFriend.totalFrequency = 0
                    localFriend.password = ""
                    localFriend.modifyTime = int(time.time())
                    print  localFriend
                    session.query(LocalUserInfoObj)
                    session.save(localFriend)
                    session.flush()
                
                    localFriend = session.query(LocalUserInfoObj).selectfirst_by(accounts = contactItem.id, skyUserID = user.userID) 
                    for phoneIndex in range(len(contactItem.phoneSeq)):
                        localFriendPhone = skyUserPhoneObj()
                        localFriendPhone.userID = localFriend.userID
                        localFriendPhone.phoneIndex = phoneIndex
                        localFriendPhone.phoneNum = contactItem.phoneSeq[phoneIndex]
                        session.query(skyUserPhoneObj)
                        session.save(localFriendPhone)
                    for sceneIndex in range(len(contactItem.sceneSeq)):
                        if contactItem.sceneSeq[sceneIndex].phoneIdx < len(contactItem.phoneSeq):
                            localFriendScene = skySceneObj()
                            localFriendScene.userID = localFriend.userID
                            localFriendScene.sceneID = sceneIndex
                            localFriendScene.phoneIndex = contactItem.sceneSeq[sceneIndex].phoneIdx
                            localFriendScene.sceneName = contactItem.sceneSeq[sceneIndex].sceneName
                            localFriendScene.touchFrequency = 0
                            session.query(skySceneObj)
                            session.save(localFriendScene)  
                        else:
                            error = "phoneNum is not in skyUserPhoneObj"
                            raise error
                
                else:
                    friend = session.query(skyUserInfoObj).selectfirst_by(accounts = contactItem.id)
                    if friend != None:
                        relation = skyUserRelationObj()
                        relation.userID = user.userID
                        relation.friendID = friend.userID
                        if len(contactItem.nameSeq) == 0:
                            relation.friendNickName = friend.nickName
                        else:
                            relation.friendNickName = contactItem.nameSeq[0]
                        relation.friendSceneID = contactItem.defaultScene
                        session.query(skyUserRelationObj)
                        session.save(relation)  
                    else:
                        error = "friend is not in the table(skyUserInfoObj)"
                        print locals()
                        raise error
                        
            transaction.commit()
        except:
            transaction.rollback()
            raise
         
        print "\nEnd add()\n"   
        return True

    def update(self, contactList):
        print "\nupdate()\n"
        print contactList
        session = sqlalchemy.create_session() 
        #session._set_echo_uow(value=True)
        transaction=session.create_transaction()
        try:
            user = session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
            for contactItem in contactList:
                sceneNameList = []
                for sceneItem in contactItem.sceneSeq:
                    sceneNameList.append(sceneItem.sceneName)
                for sceneNameItem in sceneNameList:
                    count = sceneNameList.count(sceneNameItem)
                    if count > 1:
                        error = "sceneName repeat"
                        raise error
 
                if(contactItem.id[0] == '_'):
                    if len(contactItem.sceneSeq) == 0 or len(contactItem.phoneSeq) == 0:
                        error = "localFriend  have not scene or phone"
                        raise error
                
                    localFriend = session.query(LocalUserInfoObj).selectfirst_by(accounts = contactItem.id, skyUserID = user.userID) 
                    if localFriend == None:
                        error = "localFriend is not in the table(LocalUserInfoObj)"
                        raise error
                
                    localFriend.accounts = contactItem.id
                    localFriend.searchmsg = ""
                    if len(contactItem.nameSeq) != 0:
                        localFriend.nickName = contactItem.nameSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.nickName
                    else:
                        localFriend.nickName = ""
                    if len(contactItem.emailSeq) != 0:
                        localFriend.email = contactItem.emailSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.email
                    else:
                        localFriend.email = ""
                    if len(contactItem.addrSeq) != 0:
                        localFriend.address = contactItem.addrSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.address
                    else:
                        localFriend.address = ""
                    if len(contactItem.urlSeq) != 0:
                        localFriend.myUrl = contactItem.urlSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.myUrl
                    else:
                        localFriend.myUrl = ""
                    if len(contactItem.photoSeq) != 0:
                        localFriend.myPhoto = contactItem.photoSeq[0]
                    else:
                        localFriend.myPhoto = None
                    if len(contactItem.imSeq) != 0:
                        localFriend.imTool = contactItem.imSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.imTool
                    else:
                        localFriend.imTool = ""
                    if len(contactItem.remarkSeq) != 0:
                        localFriend.remark = contactItem.remarkSeq[0]
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.remark
                    else:
                        localFriend.remark = ""
                    
                    for phoneNum in contactItem.phoneSeq:
                        localFriend.searchmsg = localFriend.searchmsg + "-" + str(phoneNum)
                        
                    localFriend.modifyTime = int(time.time())
                    localFriend.sceneID = contactItem.defaultScene
                    session.save(localFriend)
                
                    sceneMap = {}
                    localFriendSceneList = session.query(skySceneObj).select_by(userID = localFriend.userID)
                    for localFriendScene in localFriendSceneList :
                        sceneMap[localFriendScene.sceneName] = localFriendScene.touchFrequency
                        session.delete(localFriendScene)
                        session.flush()
                    userPhoneList = session.query(skyUserPhoneObj).select_by(userID = localFriend.userID) 
                    for userPhone in userPhoneList :
                        session.delete(userPhone)
                        session.flush()

                    for phoneIndex in range(len(contactItem.phoneSeq)):
                        localFriendPhone = skyUserPhoneObj()
                        localFriendPhone.userID = localFriend.userID
                        localFriendPhone.phoneIndex = phoneIndex
                        localFriendPhone.phoneNum = contactItem.phoneSeq[phoneIndex]
                        session.query(skyUserPhoneObj)
                        session.save(localFriendPhone)
                    for sceneIndex in range(len(contactItem.sceneSeq)):
                        if contactItem.sceneSeq[sceneIndex].phoneIdx < len(contactItem.phoneSeq):
                            localFriendScene = skySceneObj()
                            localFriendScene.userID = localFriend.userID
                            localFriendScene.sceneID = sceneIndex
                            localFriendScene.phoneIndex = contactItem.sceneSeq[sceneIndex].phoneIdx
                            localFriendScene.sceneName = contactItem.sceneSeq[sceneIndex].sceneName
                            localFriendScene.touchFrequency = sceneMap.get(localFriendScene.sceneName, 0)
                            session.query(skySceneObj)
                            session.save(localFriendScene)#��ӳ���?
                        else:
                            error = "phoneNum is not in skyUserPhoneObj"
                            raise error
                            
                
                else:
                    friend = session.query(skyUserInfoObj).selectfirst_by(accounts = contactItem.id)
                    relation =  session.query(skyUserRelationObj).selectfirst_by(userID = user.userID, friendID = friend.userID)
                    relation.friendNickName = contactItem.nameSeq[0]
                    relation.friendSceneID = contactItem.defaultScene
                    session.save(relation)
                    
            transaction.commit()
        except:
            transaction.rollback()
            raise
            
        print "\nEnd update()\n"
        return True

    def size(self):
        return 0

    def lastModified(self):
        print "\nlastModified()\n"
        session = sqlalchemy.create_session() 
        user = session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
        if user != None :
            return user.modifyTime
        else :
            return 0

    def getInfo(self):
        print "\ngetInfo()\n"
        session = sqlalchemy.create_session()
        userInfo = session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
        if userInfo != None :
            contact = Sky.ContactItem(id = userInfo.accounts, 
                                    nameSeq = [], 
                                    phoneSeq = [], 
                                    emailSeq = [], 
                                    addrSeq = [], 
                                    urlSeq = [], 
                                    photoSeq = [], 
                                    remarkSeq = [], 
                                    imSeq = [], 
                                    sceneSeq = [], 
                                    defaultScene = userInfo.sceneID, 
                                    lastModified = userInfo.modifyTime)
                                    
            if userInfo.nickName != "":
                contact.nameSeq.append(userInfo.nickName)   
            if userInfo.email != "":
                contact.emailSeq.append(userInfo.email)
            if userInfo.address != "":
                contact.addrSeq.append(userInfo.address)
            if userInfo.myUrl != "":
                contact.urlSeq.append(userInfo.myUrl)
            if userInfo.myPhoto != None:
                contact.photoSeq.append(userInfo.myPhoto)
            if userInfo.remark != "":
                contact.remarkSeq.append(userInfo.remark)
            if userInfo.imTool != "":
                contact.imSeq.append(userInfo.imTool)
            
            sceneList = session.query(skySceneObj).select_by(userID = userInfo.userID)
            for sceneItem in sceneList :
                contactScene = Sky.ContactScene()
                contactScene.sceneName = sceneItem.sceneName
                contactScene.touchFrequency = sceneItem.touchFrequency
                userPhone = session.query(skyUserPhoneObj).selectfirst_by(userID = userInfo.userID, phoneIndex = sceneItem.phoneIndex)
                if userPhone != None:
                    if userPhone.phoneNum not in contact.phoneSeq:
                        contact.phoneSeq.append(userPhone.phoneNum)
                    phoneIndex = contact.phoneSeq.index(userPhone.phoneNum)
                    contactScene.phoneIdx = phoneIndex
                    contact.sceneSeq.append(contactScene)
                else:
                    error = "phoneNum of the table(skySceneObj) cannot find in the table(skyUserPhoneObj)"
                    raise error
        else:
            error = "user is not in the table(skyUserInfoObj)"
            raise error
        
        print "\nEnd getInfo()\n"
        return True, contact

    def setInfo(self, contact):
        print "\nsetInfo()\n"
        sceneNameList = []
        for sceneItem in contact.sceneSeq:
            sceneNameList.append(sceneItem.sceneName)
        for sceneNameItem in sceneNameList:
            count = sceneNameList.count(sceneNameItem)
            if count > 1:
                error = "sceneName repeat"
                raise error
            
        session = sqlalchemy.create_session()
        transaction=session.create_transaction()
        try:
            userInfo = session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
            if userInfo != None :
                #userInfo.password = contact.password
                userInfo.searchmsg = ""
                if len(contact.nameSeq) != 0:
                    userInfo.nickName = contact.nameSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.nickName
                else:
                    userInfo.nickName = ""
                if len(contact.emailSeq) != 0:
                    userInfo.email = contact.emailSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.email
                else:
                    userInfo.email = ""
                if len(contact.addrSeq) != 0:
                    userInfo.address = contact.addrSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.address
                else:
                    userInfo.address = ""
                if len(contact.urlSeq) != 0:
                    userInfo.myUrl = contact.urlSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.myUrl
                else:
                    userInfo.myUrl = ""
                if len(contact.photoSeq) != 0:
                    userInfo.myPhoto = contact.photoSeq[0]
                else:
                    userInfo.myPhoto = None
                if len(contact.imSeq) != 0:
                    userInfo.imTool = contact.imSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.imTool
                else:
                    userInfo.imTool = ""
                if len(contact.remarkSeq) != 0:
                    userInfo.remark = contact.remarkSeq[0]
                    userInfo.searchmsg = userInfo.searchmsg + "-" + userInfo.remark
                else:
                    userInfo.remark = ""
                
                for phoneNum in contact.phoneSeq:
                    userInfo.searchmsg = userInfo.searchmsg + "-" + str(phoneNum)
                        
                userInfo.sceneID = contact.defaultScene
                userInfo.modifyTime = int(time.time())
                session.save(userInfo)
            
                sceneMap = {}
                userSceneList = session.query(skySceneObj).select_by(userID = userInfo.userID) 
                for userScene in userSceneList :
                    sceneMap[userScene.sceneName] = userScene.touchFrequency
                    session.delete(userScene)
                    session.flush()

                userPhoneList = session.query(skyUserPhoneObj).select_by(userID = userInfo.userID) 
                for userPhone in userPhoneList :
                    session.delete(userPhone)
                    session.flush()
                        
                for phoneIndex in range(len(contact.phoneSeq)):
                    userPhone = skyUserPhoneObj()
                    userPhone.userID = userInfo.userID
                    userPhone.phoneIndex = phoneIndex
                    userPhone.phoneNum = contact.phoneSeq[phoneIndex]
                    session.query(skyUserPhoneObj)
                    session.save(userPhone)
                    
                for sceneIndex in range(len(contact.sceneSeq)):
                    if contact.sceneSeq[sceneIndex].phoneIdx < len(contact.phoneSeq):
                        userScene = skySceneObj()
                        userScene.userID = userInfo.userID
                        userScene.sceneID = sceneIndex
                        userScene.phoneIndex = contact.sceneSeq[sceneIndex].phoneIdx
                        userScene.sceneName = contact.sceneSeq[sceneIndex].sceneName
                        userScene.touchFrequency = sceneMap.get(userScene.sceneName, 0)
                        session.query(skySceneObj)
                        session.save(userScene)
                    else:
                        error = "phoneNum is not in skyUserPhoneObj"
                        raise error
            else:
                error = "user is not in the table(skyUserInfoObj)"
                raise error
                
            transaction.commit()
        except:
            transaction.rollback()
            raise
        
        print "\nEnd setInfo()\n"
        return True
    
    def incrementFrequency(self, id, sceneIdx):
        print "\incrementFrequency()\n"
        session = sqlalchemy.create_session()
        transaction=session.create_transaction()
        try:
            if(id[0] == '_'):
                userInfo = session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
                localFriendInfo = session.query(LocalUserInfoObj).selectfirst_by(accounts = id, skyUserID = userInfo.userID) 
                if localFriendInfo == None:
                    error = "localFriend is not in the table(LocalUserInfoObj)"
                    raise error
                localFriendInfo.totalFrequency = localFriendInfo.totalFrequency + 1
                session.save(localFriendInfo)
                
                sceneItem = session.query(skySceneObj).selectfirst_by(userID = localFriendInfo.userID, sceneID = sceneIdx)
                if sceneItem == None:
                    error = "scene is not in the table(skySceneObj)"
                    raise error
                sceneItem.touchFrequency = sceneItem.touchFrequency + 1
                session.save(sceneItem)
                
            else:    
                friendInfo = session.query(skyUserInfoObj).selectfirst_by(accounts = id)
                if friendInfo == None:
                    error = "user is not in the table(skyUserInfoObj)"
                    raise error
                friendInfo.totalFrequency = friendInfo.totalFrequency + 1
                session.save(friendInfo)
            
                sceneItem = session.query(skySceneObj).selectfirst_by(userID = friendInfo.userID, sceneID = sceneIdx)
                if sceneItem == None:
                    error = "scene is not in the table(skySceneObj)"
                    raise error
                sceneItem.touchFrequency = sceneItem.touchFrequency + 1
                session.save(sceneItem)

            transaction.commit()
        except:
            transaction.rollback()
            raise
            
        print "\nEnd incrementFrequency()\n"
        return
    
    def beginExport(self):
        print "\nbeginExport()\n"
        self.session = sqlalchemy.create_session() 
        user = self.session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
        if user == None:
            error = "user is not in the table(skyUserInfoObj)"
            raise error
        
        self.transaction = self.session.create_transaction()
        try:
            localFriendList = self.session.query(LocalUserInfoObj).select_by(skyUserID = user.userID)
            for localFriend in localFriendList:
                localFriendSceneList = self.session.query(skySceneObj).select_by(userID = localFriend.userID)
                for localFriendScene in localFriendSceneList :
                    self.session.query(skySceneObj_bak1)
                    self.session.save(localFriendScene)
                    self.session.query(skySceneObj)
                    self.session.delete(localFriendScene)
                    self.session.flush()
                userPhoneList = self.session.query(skyUserPhoneObj).select_by(userID = localFriend.userID) 
                for userPhone in userPhoneList :
                    self.session.query(skyUserPhoneObj_bak1)
                    self.session.save(userPhone)
                    self.session.query(skyUserPhoneObj)
                    self.session.delete(userPhone)
                    self.session.flush()
                   
                self.session.query(LocalUserInfoObj_bak1)
                self.session.save(localFriend)
                self.session.query(LocalUserInfoObj)
                self.session.delete(localFriend)
                self.session.flush()
        except:
            self.transaction.rollback()
            raise
        
        self.timer = threading.Timer(30.0, rollback)
        self.timer.start()
        
        print "\nend beginExport()\n"
        return True
    
    def endExport(self):
        print "\nendExport()\n"
        self.timer.cancel()
        self.transaction.commit()
        self.transaction = None
        print "\nend endExport()\n"
        return True
    
    def rollback(self):
        print "\nrollback()\n"
        self.timer.cancel()
        self.transaction.rollback()
        self.transaction = None
        print "\nend rollback()\n"
        return True
    
    def export(self, contacts):
        print "\nexport()\n"
        if self.transaction == None:
            error = "time out"
            raise error
        
        self.timer.cancel()
        
        user = self.session.query(skyUserInfoObj).selectfirst_by(accounts = self.id_)
        if user == None:
            error = "user is not in the table(skyUserInfoObj)"
            raise error
        
        localFriend = LocalUserInfoObj()
        localFriendPhone = skyUserPhoneObj()
        localFriendScene = skySceneObj()
        localFriend.skyUserID = user.userID
        
        formattedAddr = ""
        addr = ""
        name = ""
        formattedName = ""
        nickName = ""
        account = ""
        
        try: 
            for contact in contacts:
                localFriend.searchmsg = ""
                for contactField in contact:
                    if contactField.fieldID == 100:
                        addr = contactField.attrValueArray[6] + contactField.attrValueArray[4] + contactField.attrValueArray[3] + contactField.attrValueArray[2]
                    if contactField.fieldID == 104:
                        formattedAddr = contactField.attrValueArray[0]
                    if contactField.fieldID == 105: 
                        formattedName = contactField.attrValueArray[0]
                    if contactField.fieldID == 106:
                        name = contactField.attrValueArray[0] + contactField.attrValueArray[1]    
                    if contactField.fieldID == 107:
                        nickName = contactField.attrValueArray[0]
                    if contactField.fieldID == 115:
                        phoneNum = contactField.attrValueArray[0]
                        localFriendPhone.phoneNum = phoneNum
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriendPhone.phoneNum
                    if contactField.fieldID == 103:
                        email = contactField.attrValueArray[0]
                        localFriend.email = email
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.email
                    if contactField.fieldID == 118:
                        url = contactField.attrValueArray[0]
                        localFriend.myUrl = url
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.myUrl
                    if contactField.fieldID == 108:
                        remark = contactField.attrValueArray[0]
                        localFriend.remark = remark
                        localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.remark
                    if contactField.fieldID == 110:
                        photo = contactField.attrValueArray[0]
                        localFriend.myPhoto = photo
                        
                if formattedAddr != "":
                    localFriend.address = formattedAddr
                else:
                    localFriend.address = addr
                localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.address
                        
                if formattedName != "":
                    localFriend.nickName = formattedName
                    account = formattedName
                    localFriendScene.sceneName = formattedName
                elif name != "":
                    localFriend.nickName = name
                    account = name
                    localFriendScene.sceneName = name
                else:
                    localFriend.nickName = nickName
                    account = nickName
                    localFriendScene.sceneName = nickName
                localFriend.searchmsg = localFriend.searchmsg + "-" + localFriend.nickName
                    
                localFriendList = self.session.query(LocalUserInfoObj).select_by(nickName = account, skyUserID = user.userID)
                account = "_" + account + str(localFriendList)
                localFriend.accounts = account
                
                print localFriend.searchmsg              
                    
                self.session.query(LocalUserInfoObj)
                self.session.save(localFriend)
                self.session.flush()
                localFriend = self.session.query(LocalUserInfoObj).selectfirst_by(accounts = account, skyUserID = user.userID)
                localFriendPhone.userID = localFriend.userID
                localFriendPhone.phoneIndex = 0
                self.session.query(skyUserPhoneObj)
                self.session.save(localFriendPhone)
                self.session.flush()
                
                localFriendScene.userID = localFriend.userID
                localFriendScene.sceneID = 0
                localFriendScene.phoneIndex = 0
                localFriendScene.touchFrequency = 0
                self.session.query(skySceneObj)
                self.session.save(localFriendScene)
                self.session.flush()
        except:
            self.transaction.rollback()
            raise
        
        self.timer = threading.Timer(30.0,  rollback)
        self.timer.start()
        
        print "\nEnd export()\n"
        return

class SkySecManager():
    def __init__(self):
        pass
    def logIn(self, id, pwd):
        print "\nlogIn()\n"
        session = sqlalchemy.create_session()
        resultList = session.query(skyUserInfoObj).select_by(accounts = id, password = pwd)
        if len(resultList) == 0 :
            error = "user is not in the table(skyUserPhoneObj)"
            raise error

        print "\nEnd logIn()\n"
        return True

    def signIn(self, info):  
        print "\nsignIn()\n"  
        session = sqlalchemy.create_session()
        result = session.query(skyUserInfoObj).selectfirst_by(accounts = info.account)
        if result != None :
            error = "user is in the table(skyUserPhoneObj)"
            raise error
            
        user_info = skyUserInfoObj()
        user_info.accounts = info.account
        if info.nickname == '':
            user_info.nickName = info.account
        else:
            user_info.nickName = info.nickname
        user_info.searchmsg = user_info.searchmsg + "-" + user_info.nickName
        user_info.sceneID = 0
        user_info.password = info.password
        user_info.modifyTime = 0
        session.save(user_info)
        session.flush()   
        
        print "\nEnd signIn()\n"  
        return True
    
    def check(self, id):
        print locals()
        return True

    def getCode(self, id):
        print locals()
        return True 

class ThreadingServer(ThreadingMixIn, SimpleXMLRPCServer):
    """ 这个类是简单的继承ThreadingMixIn, SimpleXMLRPCServer类，实现其功能!"""
    pass

class Server():
    def __init__(self):
        pass
    def run(self):
        dbengine = sqlalchemy.create_engine(g_DBConnectionStr, echo=False, auto_identity_insert = False)
        skyUserInfoTable = sqlalchemy.Table('skyUserInfo', dbengine
                                            , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                            , sqlalchemy.Column('accounts', String(20))
                                            , sqlalchemy.Column('password', String(8))
                                            , sqlalchemy.Column('nickName', String(50))
                                            , sqlalchemy.Column('email', String(50))
                                            , sqlalchemy.Column('address', String(100))
                                            , sqlalchemy.Column('myUrl', String(50))
                                            , sqlalchemy.Column('myPhoto', String())
                                            , sqlalchemy.Column('imTool', String(50))
                                            , sqlalchemy.Column('sceneID', Integer, primary_key = False, autoincrement=False)
                                            , sqlalchemy.Column('totalFrequency', Integer, primary_key = False, autoincrement=False)
                                            , sqlalchemy.Column('remark', String(100))
                                            , sqlalchemy.Column('searchmsg', String(300))
                                            , sqlalchemy.Column('modifyTime', Integer, primary_key = False, autoincrement=False))
        skyUserRelationTable = sqlalchemy.Table('skyUserRelation', dbengine
                                                , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                                , sqlalchemy.Column('friendID', Integer, primary_key = True, autoincrement=False)
                                                , sqlalchemy.Column('friendNickName', String(50))
                                                , sqlalchemy.Column('friendSceneID', Integer, primary_key = False, autoincrement=False))
        skySceneTable = sqlalchemy.Table('skyScene', dbengine
                                        , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                        , sqlalchemy.Column('sceneID', Integer, primary_key = True, autoincrement=False)
                                        , sqlalchemy.Column('phoneIndex', Integer, primary_key = False, autoincrement=False)
                                        , sqlalchemy.Column('sceneName', String(50))
                                        , sqlalchemy.Column('touchFrequency', Integer, primary_key = False, autoincrement=False))
        skySceneTable_bak1 = sqlalchemy.Table('skyScene_bak1', dbengine
                                            , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                            , sqlalchemy.Column('sceneID', Integer, primary_key = True, autoincrement=False)
                                            , sqlalchemy.Column('phoneIndex', Integer, primary_key = False, autoincrement=False)
                                            , sqlalchemy.Column('sceneName', String(50))
                                            , sqlalchemy.Column('touchFrequency', Integer, primary_key = False, autoincrement=False))
        LocalUserInfoTable = sqlalchemy.Table('LocalUserInfo', dbengine
                                            , sqlalchemy.Column('skyUserID', Integer, primary_key = True, autoincrement=False)
                                            , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                            , sqlalchemy.Column('accounts', String(20))
                                            , sqlalchemy.Column('password', String(8))
                                            , sqlalchemy.Column('nickName', String(50))
                                            , sqlalchemy.Column('email', String(50))
                                            , sqlalchemy.Column('address', String(100))
                                            , sqlalchemy.Column('myUrl', String(50))
                                            , sqlalchemy.Column('myPhoto', String())
                                            , sqlalchemy.Column('imTool', String(50))
                                            , sqlalchemy.Column('sceneID', Integer, primary_key = False, autoincrement=False)
                                            , sqlalchemy.Column('totalFrequency', Integer, primary_key = False, autoincrement=False)
                                            , sqlalchemy.Column('remark', String(100))
                                            , sqlalchemy.Column('searchmsg', String(300))
                                            , sqlalchemy.Column('modifyTime', Integer, primary_key = False, autoincrement=False))
        LocalUserInfoTable_bak1 = sqlalchemy.Table('LocalUserInfo_bak1', dbengine
                                                , sqlalchemy.Column('skyUserID', Integer, primary_key = True, autoincrement=False)
                                                , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                                , sqlalchemy.Column('accounts', String(20))
                                                , sqlalchemy.Column('password', String(8))
                                                , sqlalchemy.Column('nickName', String(50))
                                                , sqlalchemy.Column('email', String(50))
                                                , sqlalchemy.Column('address', String(100))
                                                , sqlalchemy.Column('myUrl', String(50))
                                                , sqlalchemy.Column('myPhoto', String())
                                                , sqlalchemy.Column('imTool', String(50))
                                                , sqlalchemy.Column('sceneID', Integer, primary_key = False, autoincrement=False)
                                                , sqlalchemy.Column('totalFrequency', Integer, primary_key = False, autoincrement=False)
                                                , sqlalchemy.Column('remark', String(100))
                                                , sqlalchemy.Column('searchmsg', String(300))
                                                , sqlalchemy.Column('modifyTime', Integer, primary_key = False, autoincrement=False))
        skyUserPhoneTable = sqlalchemy.Table('skyUserPhone', dbengine
                                            , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                            , sqlalchemy.Column('phoneIndex', Integer, primary_key = True, autoincrement=False)
                                            , sqlalchemy.Column('phoneNum', String(20))
                                            , sqlalchemy.Column('description', String(50)))
        skyUserPhoneTable_bak1 = sqlalchemy.Table('skyUserPhone_bak1', dbengine
                                                , sqlalchemy.Column('userID', Integer, primary_key = True, autoincrement=False)
                                                , sqlalchemy.Column('phoneIndex', Integer, primary_key = True, autoincrement=False)
                                                , sqlalchemy.Column('phoneNum', String(20))
                                                , sqlalchemy.Column('description', String(50)))
        
        sqlalchemy.mapper(skyUserPhoneObj, skyUserPhoneTable)
        sqlalchemy.mapper(skyUserPhoneObj_bak1, skyUserPhoneTable_bak1)
        sqlalchemy.mapper(skyUserRelationObj, skyUserRelationTable)
        sqlalchemy.mapper(skySceneObj, skySceneTable)
        sqlalchemy.mapper(skySceneObj_bak1, skySceneTable_bak1)
        sqlalchemy.mapper(skyUserInfoObj, skyUserInfoTable)
        sqlalchemy.mapper(LocalUserInfoObj, LocalUserInfoTable) 
        sqlalchemy.mapper(LocalUserInfoObj_bak1, LocalUserInfoTable_bak1) 

        
if __name__ == "__main__":
        contacts = []
        contact = []
        contact2 = []
        
        Field_nickname = contactField()
        Field_nickname.fieldID = 106
        Field_nickname.attrValueArray.append("xie")
        Field_nickname.attrValueArray.append("haiping")
        contact.append(Field_nickname)
        
        Field_addr = contactField()
        Field_addr.fieldID = 104
        Field_addr.attrValueArray.append("jiangxi fuzhou pengtian")
        contact.append(Field_addr)
        
        Field_phone = contactField()
        Field_phone.fieldID = 115
        Field_phone.attrValueArray.append("13480737672")
        contact.append(Field_phone)
        
        Field_email = contactField()
        Field_email.fieldID = 103
        Field_email.attrValueArray.append("64happy@gmail.com")
        contact.append(Field_email)
        
        Field_url = contactField()
        Field_url.fieldID = 118
        Field_url.attrValueArray.append("www.sina.com.cn")
        contact.append(Field_url)
        
        Field_remark = contactField()
        Field_remark.fieldID = 108
        Field_remark.attrValueArray.append("helloworld")
        contact.append(Field_remark)
        
        contacts.append(contact)
        
        
        Field_nickname2 = contactField()
        Field_nickname2.fieldID = 106
        Field_nickname2.attrValueArray.append("xu")
        Field_nickname2.attrValueArray.append("hong")
        contact2.append(Field_nickname2)
        
        Field_addr2 = contactField()
        Field_addr2.fieldID = 104
        Field_addr2.attrValueArray.append("shichuang luzhou")
        contact2.append(Field_addr2)
        
        Field_phone2 = contactField()
        Field_phone2.fieldID = 115
        Field_phone2.attrValueArray.append("13411111111")
        contact2.append(Field_phone2)
        
        Field_email2 = contactField()
        Field_email2.fieldID = 103
        Field_email2.attrValueArray.append("xuhong@gmail.com")
        contact2.append(Field_email2)
        
        Field_url2 = contactField()
        Field_url2.fieldID = 118
        Field_url2.attrValueArray.append("www.sohu.com.cn")
        contact2.append(Field_url2)
        
        Field_remark2 = contactField()
        Field_remark2.fieldID = 108
        Field_remark2.attrValueArray.append("hellotmd")
        contact2.append(Field_remark2)
        
        contacts.append(contact2)
        
        pim = SkyPimManager("xhp")
        pim.export(contacts)
     


